import requests
from datetime import datetime
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def get_exchange_rate(base_currency, target_currency):
    """
    获取两种货币之间的汇率，基础货币汇率固定为1
    """
    result = {
        "base_currency": base_currency,
        "target_currency": target_currency,
        "base_rate": "1",
        "target_rate": "",
        "timestamp":datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    try:
        url = f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{base_currency.lower()}.json"
        #logging.info(f"请求汇率API: {url}")

        response = requests.get(url, timeout=10)
        response.raise_for_status()  # 抛出HTTP错误状态码

        data = response.json()
        base_key = base_currency.lower()
        target_key = target_currency.lower()

        if base_key in data and target_key in data[base_key]:
            result["target_rate"] = str(data[base_key][target_key])
            # logging.info(f"成功获取 {base_currency} 到 {target_currency} 的汇率: {result['target_rate']}")
        else:
            logging.warning(f"汇率数据中未找到 {target_currency} 的信息")

    except requests.exceptions.RequestException as e:
        logging.error(f"汇率API请求失败: {str(e)}")
    except Exception as e:
        logging.error(f"处理汇率数据时出错: {str(e)}")

    return result


def calculate_exchange(base_currency, target_currency, base_price):
    """
    计算货币转换后的金额，包含完整的货币信息
    """
    result = {
        "base_currency": base_currency,
        "target_currency": target_currency,
        "base_rate": "1",
        "target_rate": "",
        "base_price": str(base_price),
        "target_price": "",
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "status": "失败"
    }

    try:
        # 获取汇率信息
        rate_info = get_exchange_rate(base_currency, target_currency)

        if rate_info["target_rate"]:
            result["target_rate"] = rate_info["target_rate"]
            exchange_rate = float(rate_info["target_rate"])
            target_price = float(base_price) * exchange_rate
            result["target_price"] = f"{target_price:.2f}"
            result["status"] = "成功"
            logging.info(f"货币转换成功: {base_price} {base_currency} = {result['target_price']} {target_currency}")
        else:
            logging.warning(f"无法进行货币转换，未获取到有效汇率")

    except Exception as e:
        logging.error(f"货币转换计算失败: {str(e)}")

    return result
